package cur.nature.admin.common.log;

import cur.nature.admin.common.config.AppContextUtil;
import cur.nature.admin.service.Admin_LogService;
import cur.nature.admin.model.vo.Admin_LogVO;
import cur.nature.framework.core.log.LOG;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentLinkedQueue;

@Component
public class LogTaskHelper {

    @Autowired
    private Admin_LogService logService;
    // 创建一个并发链表队列
    private ConcurrentLinkedQueue<Admin_LogVO> queue = new ConcurrentLinkedQueue<>();

    @PostConstruct
    public void init() {
        LOG.info("创建日志处理线程...");
        // 创建一个线程来专门处理日志记录
        new Thread(() -> {
            // 插入日志
            while (true) {
                try {
                    while (!queue.isEmpty()) {
                        logService.save(queue.poll());
                    }
                    Thread.sleep(10000L); // 等 10 秒
                } catch (Exception e) {
                    LOG.warn("插入日志异常。。" + e.getMessage());
                }
            }
        }).start();
    }

    public void putLog(HttpServletRequest request, Long spentTime, String param) {
        // 记录日志
        final String userId = AppContextUtil.getUserId(request);
        String ipAddr = AppContextUtil.getIpAddr(request);
        final String uri = request.getRequestURI();
        this.putTask(uri, userId, spentTime, param,true, ipAddr);
    }

    public void putTask(String url, String userId, Long  spentTime, String param, boolean isSuccess, String ip) {
        Admin_LogVO vo = new Admin_LogVO();
        vo.setCode(url);
        vo.setIp(ip);
        vo.setParam(param);
        vo.setOperator(userId);
        vo.setSpentTime(spentTime);
        vo.setOperateType(1);
        vo.setResult(isSuccess ? 1 : 0);
        queue.offer(vo);
    }


}
